var express = require('express');
var router = express.Router();


// 查找数据并显示
router.get('/userlist',function(req,res,next){
  var db=req.db;
  var collection = db.get('userinfo');
  collection.find({},{},function(e,docs){
      res.render('userview/userlist',{
        'userlist':docs
      })
      // res.json(docs);
  })
})

//增加数据的页面
router.get('/newuser',function(req,res,next){
  res.render('userview/newuser',{title : 'Add New User'});
});

//上传增加的数据并显示
router.post('/adduser',function(req,res,next){
  
 var db=req.db;

 var username=req.body.username;
 var age=req.body.age;
 var email=req.body.email;
 var fullname=req.body.fullname;
 var location=req.body.location;
 var like1=req.body.like1;
 var like2=req.body.like2;
 var like3=req.body.like3;
//  var gender=req.body.gender.value;

 var collection = db.get('userinfo');

 collection.insert({
  "username" :username,
  "age":age,
  "email":email,
  "fullname":fullname,
  "location": location,
  "like":
  {
    "1": like1,
    "2":like2,
    "3":like3,
  }
  // "gender":gender

 }),function(err,doc){
   if (err) {
    res.send("There was a problem adding the information to the database.");
   }
   else{
    
    res.redirect("userview//userlist");
   }
 }
})

//增加删除的页面
router.get('/removeuser',function(req,res,next){
  res.render('userview/removeuser',{title : 'Remove User'});
});


//删除操作
router.post('/deleteuser',function(req,res,next){
    
    var db= req.db;
    var collection=db.get('userinfo');
    var userToDetele = req.body.username;
    collection.remove({'username':userToDetele},function(err){
        res.send((err === null)?{msg:'删除成功'}:{msg:'error:' + err});
    })
})

// 增加查找页面
router.get('/find',function(req,res,next){
  res.render('userview/find',{title : 'Find By Username'});
});


//显示查找结果
router.get('/findone',function(req,res,next){
  var db=req.db;
  var collection = db.get('userinfo');
  var username=req.query.username;

  collection.find({'username':username },{},function(e,docs){
      res.render('userview/showfind',{
        'showfind':docs
      })
  })
})


module.exports = router;
